<template>
  <div class="config-page">
    <t-card title="快代理配置" class="config-card">
      <t-table
        ref="proxyTableRef"
        row-key="key"
        :columns="proxyColumns"
        :data="proxyTableData"
        :hover="hover"
        :stripe="stripe"
        :editable-row-keys="proxyEditableRowKeys"
        table-layout="fixed"
        bordered
        :loading="proxyLoading"
        :row-height="80"
      >
        <!-- App ID列 -->
        <template #secret_id="{ row }">
          <div class="proxy-cell">
            <div v-if="isProxyEditing(row.key)">
              <t-input
                v-model="proxyEditMap[row.key]?.editedRow.secret_id"
                :maxlength="50"
                :autoWidth="false"
                clearable
              />
            </div>
            <div v-else class="proxy-content">
              <span class="proxy-text">
                {{ getMaskedContent(row.secret_id) }}
              </span>
              <t-popup
                placement="top"
                :content="row.secret_id"
                :show-arrow="true"
                trigger="click"
              >
                <t-button variant="text" size="small">
                  查看
                </t-button>
              </t-popup>
            </div>
          </div>
        </template>

        <!-- App Key列 -->
        <template #secret_key="{ row }">
          <div class="proxy-cell">
            <div v-if="isProxyEditing(row.key)">
              <t-input
                v-model="proxyEditMap[row.key]?.editedRow.secret_key"
                :maxlength="50"
                :autoWidth="false"
                clearable
              />
            </div>
            <div v-else class="proxy-content">
              <span class="proxy-text">
                {{ getMaskedContent(row.secret_key) }}
              </span>
              <t-popup
                placement="top"
                :content="row.secret_key"
                :show-arrow="true"
                trigger="click"
              >
                <t-button variant="text" size="small">
                  查看
                </t-button>
              </t-popup>
            </div>
          </div>
        </template>

        <!-- 用户名列 -->
        <template #username="{ row }">
          <div class="proxy-cell">
            <div v-if="isProxyEditing(row.key)">
              <t-input
                v-model="proxyEditMap[row.key]?.editedRow.username"
                :maxlength="50"
                :autoWidth="false"
                clearable
              />
            </div>
            <div v-else class="proxy-content">
              <span class="proxy-text">
                {{ getMaskedContent(row.username) }}
              </span>
              <t-popup
                placement="top"
                :content="row.username"
                :show-arrow="true"
                trigger="click"
              >
                <t-button variant="text" size="small">
                  查看
                </t-button>
              </t-popup>
            </div>
          </div>
        </template>

        <!-- 密码列 -->
        <template #password="{ row }">
          <div class="proxy-cell">
            <div v-if="isProxyEditing(row.key)">
              <t-input
                v-model="proxyEditMap[row.key]?.editedRow.password"
                :maxlength="50"
                :autoWidth="false"
                clearable
              />
            </div>
            <div v-else class="proxy-content">
              <span class="proxy-text">
                {{ getMaskedContent(row.password) }}
              </span>
              <t-popup
                placement="top"
                :content="row.password"
                :show-arrow="true"
                trigger="click"
              >
                <t-button variant="text" size="small">
                  查看
                </t-button>
              </t-popup>
            </div>
          </div>
        </template>

        <!-- 操作栏 -->
        <template #operate="{ row }">
          <div class="table-operations">
            <t-space>
              <t-button
                v-if="!isProxyEditing(row.key)"
                variant="text"
                theme="primary"
                :disabled="row.status === -1"
                @click="onProxyEdit($event)"
                :data-id="row.key"
              >
                编辑
              </t-button>
              <template v-else>
                <t-button
                  variant="text"
                  theme="primary"
                  @click="onProxySave($event)"
                  :data-id="row.key"
                >
                  保存
                </t-button>
                <t-button
                  variant="text"
                  theme="danger"
                  @click="onProxyCancel($event)"
                  :data-id="row.key"
                >
                  取消
                </t-button>
              </template>
            </t-space>
          </div>
        </template>

        <!-- 状态列 -->
        <template #status="{ row }">
          <t-tag :theme="getStatusTheme(row.status)" variant="light-outline">
            {{ getStatusText(row.status) }}
          </t-tag>
        </template>
      </t-table>
    </t-card>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import { Input, MessagePlugin, Table, Button, Space, Card, Tag, Popup } from 'tdesign-vue';

// 定义状态样式映射
const STATUS_STYLE_MAP: Record<number, { text: string; color: string }> = {
  0: { text: '生效中', color: '#0052D9' },
  [-1]: { text: '已失效', color: '#FFAA00' },
  [-2]: { text: '未创建', color: '#999999' },
};

// 定义接口
interface ProxyRow {
  key: string;
  provider: string;
  secret_id: string;
  secret_key: string;
  status: number;
}

export default Vue.extend({
  name: 'ProxyConfig',

  components: {
    't-table': Table,
    't-button': Button,
    't-space': Space,
    't-card': Card,
    't-tag': Tag,
    't-input': Input,
    't-popup': Popup,
  },

  data() {
    return {
      proxyLoading: false,
      hover: true,
      stripe: false,
      proxyEditableRowKeys: [] as string[],
      proxyTableData: [] as ProxyRow[],
      proxyEditMap: {} as Record<string, { rowIndex: number; editedRow: ProxyRow }>,
      proxyColumns: [
        {
          title: '代理商',
          colKey: 'provider',
          width: 120,
          align: 'left',
          editable: false,
        },
        {
          title: '用户名',
          colKey: 'username',
          width: 180,
          align: 'left',
          cell: 'username',
        },
        {
          title: '密码',
          colKey: 'password',
          width: 180,
          align: 'left',
          cell: 'password',
        },
        {
          title: 'Secret ID',
          colKey: 'secret_id',
          width: 180,
          align: 'left',
          cell: 'secret_id',
        },
        {
          title: 'Secret Key',
          colKey: 'secret_key',
          width: 180,
          align: 'left',
          cell: 'secret_key',
        },
        {
          title: '状态',
          colKey: 'status',
          width: 120,
          align: 'center',
          cell: 'status',
        },
        {
          title: '操作',
          colKey: 'operate',
          width: 120,
          align: 'center',
          fixed: 'right',
        },
      ],
    };
  },

  created() {
    this.initProxyData();
  },

  methods: {
    // 获取状态对应的文本
    getStatusText(status: number): string {
      return STATUS_STYLE_MAP[status]?.text || '未知状态';
    },

    // 获取状态对应的主题色
    getStatusTheme(status: number): string {
      const themeMap = {
        0: 'success',
        [-1]: 'warning',
        [-2]: 'default',
      };
      return themeMap[status] || 'default';
    },

    // 初始化快代理数据
    initProxyData() {
      this.proxyTableData = [{
        key: 'kuaidaili',
        provider: '快代理',
        secret_id: '',
        secret_key: '',
        status: -2, // 未创建状态
      }];
      this.fetchProxyConfigs();
    },

    // 检查快代理行是否处于编辑状态
    isProxyEditing(key: string): boolean {
      return this.proxyEditableRowKeys.includes(key);
    },

    // 快代理编辑操作
    onProxyEdit(event: Event): void {
      const target = event.currentTarget as HTMLElement;
      const id = target.getAttribute('data-id');
      if (id) {
        // 清除之前的编辑状态
        this.proxyEditableRowKeys = [];
        // 添加新的编辑行
        this.proxyEditableRowKeys.push(id);
        const rowIndex = this.proxyTableData.findIndex((row) => row.key === id);
        if (rowIndex !== -1) {
          const currentRow = this.proxyTableData[rowIndex];
          // 将当前行数据存储到 proxyEditMap 中
          // 清除之前的编辑数据
          this.proxyEditMap = {};
          this.$set(this.proxyEditMap, id, {
            rowIndex,
            editedRow: {
              key: currentRow.key,
              provider: currentRow.provider,
              secret_id: currentRow._id || '',
              secret_key: currentRow.secret_key || '',
              status: currentRow.status,
            },
          });
        }
      }
    },

    // 快代理取消编辑
    onProxyCancel(event: Event): void {
      const target = event.currentTarget as HTMLElement;
      const id = target.getAttribute('data-id');
      if (id) {
        // 清除编辑状态
        this.proxyEditableRowKeys = [];
        // 清除编辑数据
        this.proxyEditMap = {};
      }
    },

    // 处理内容显示
    getMaskedContent(content: string): string {
      if (!content) return '暂无信息';
      return '*'.repeat(20); // 统一显示固定长度的掩码
    },

    // 快代理保存操作
    async onProxySave(event: Event): Promise<void> {
      const target = event.currentTarget as HTMLElement;
      const id = target.getAttribute('data-id');
      if (!id) return;

      try {
        const current = this.proxyEditMap[id];
        if (!current) {
          MessagePlugin.error('未找到要保存的数据');
          return;
        }

        const rowData = current.editedRow;
        
        // 验证必填字段
        if (!rowData.username || !rowData.password || !rowData.secret_id || !rowData.secret_key) {
          MessagePlugin.error('所有代理配置信息都不能为空');
          return;
        }

        const isExisting = !id.startsWith('kuaidaili');
        let response;
        if (isExisting) {
          response = await this.$request.put(`/system/proxy-configs/${rowData.key}/`, {
            provider: rowData.provider,
            username: rowData.username,
            password: rowData.password,
            secret_id: rowData.secret_id,
            secret_key: rowData.secret_key,
          });
        } else {
          response = await this.$request.post('/system/proxy-configs/', {
            provider: rowData.provider,
            username: rowData.username,
            password: rowData.password,
            secret_id: rowData.secret_id,
            secret_key: rowData.secret_key,
          });
        }

        if (response?.code === 0 || response?.status === 200) {
          MessagePlugin.success('保存成功');
          this.updateProxyEditState(id);

          if (!isExisting && response.data?.id) {
            // 更新表格中的数据
            const updatedRow = {
              ...rowData,
              key: String(response.data.id),
              secret_id: response.data.secret_id,
              secret_key: response.data.secret_key,
              status: 0, // 设置为生效中
            };
            this.proxyTableData.splice(current.rowIndex, 1, updatedRow);
          }

          // 刷新数据
          await this.fetchProxyConfigs();
        } else {
          MessagePlugin.error(response?.message || '保存失败');
        }
      } catch (error) {
        console.error('保存失败:', error);
        MessagePlugin.error('保存过程中出现错误');
      }
    },

    // 更新快代理编辑状态
    updateProxyEditState(id: string): void {
      // 清除编辑状态
      this.proxyEditableRowKeys = [];
      // 清除编辑数据
      this.proxyEditMap = {};
    },

    // 获取快代理配置
    async fetchProxyConfigs(): Promise<void> {
      this.proxyLoading = true;
      try {
        const response = await this.$request.get('/system/proxy-configs/');
        if (response.status === 200) {
          // 如果有配置数据
          if (response.data && response.data.length > 0) {
            const proxyConfig = response.data[0]; // 假设只有一个配置
            this.proxyTableData = [{
              key: String(proxyConfig.id), // 确保 key 是字符串类型
              provider: '快代理',
              secret_id: proxyConfig.secret_id || '',
              secret_key: proxyConfig.secret_key || '',
              status: proxyConfig.status,
            }];
          } else {
            // 如果没有配置数据，显示默认行
            this.proxyTableData = [{
              key: 'kuaidaili',
              provider: '快代理',
              secret_id: '',
              secret_key: '',
              status: -2, // 未创建状态
            }];
          }
          // 清除编辑状态
          this.proxyEditableRowKeys = [];
          this.proxyEditMap = {};
        }
      } catch (error) {
        MessagePlugin.error('加载快代理配置失败');
        console.error('加载快代理配置失败:', error);
      } finally {
        this.proxyLoading = false;
      }
    },
  },
});
</script>

<style lang="less" scoped>
.config-page {
  padding: 20px;

  .config-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.05);
  }

  .table-operations {
    .t-button {
      padding: 0 4px;
      
      &:hover {
        background-color: rgba(0, 0, 0, 0.04);
      }
    }
  }

  .proxy-cell {
    .proxy-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .proxy-text {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        margin-right: 8px;
        word-break: break-all;
      }
    }
  }

  // 添加弹出层样式
  :deep(.t-popup) {
    max-width: 500px;
    word-break: break-all;
    white-space: pre-wrap;
  }
}
</style> 